package ui.swing.textcomponent;

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class TextField_ColWidth_Document extends JFrame {

	private static final long serialVersionUID = -9127496649251585301L;

	public TextField_ColWidth_Document() {
		super("JTextField Test");

		getContentPane().setLayout(new FlowLayout());

		JTextField textField1 = new JTextField("m", 1);
		JTextField textField2 = new JTextField("mm", 2);
		JTextField textField3 = new JTextField("mmm", 3);
		JTextField textField4 = new JTextField("mmmm", 4);
		JTextField textField5 = new JTextField("mmmmm", 5);
		JTextField textField6 = new JTextField("mmmmmm", 6);
		JTextField textField7 = new JTextField("mmmmmmm", 7);
		JTextField textField8 = new JTextField("mmmmmmmm", 8);
		JTextField textField9 = new JTextField("mmmmmmmmm", 9);
		JTextField textField10 = new JTextField("mmmmmmmmmm", 10);
		JTextField textField11 = new JTextField("mmmmmmmmmmm", 11);
		JTextField textField12 = new JTextField("mmmmmmmmmmmm", 12);
		JTextField textField13 = new JTextField("mmmmmmmmmmmmm", 13);
		JTextField textField14 = new JTextField("mmmmmmmmmmmmmm", 14);

		getContentPane().add(textField1);
		getContentPane().add(textField2);
		getContentPane().add(textField3);
		getContentPane().add(textField4);
		getContentPane().add(textField5);
		getContentPane().add(textField6);
		getContentPane().add(textField7);
		getContentPane().add(textField8);
		getContentPane().add(textField9);
		getContentPane().add(textField10);
		getContentPane().add(textField11);
		getContentPane().add(textField12);
		getContentPane().add(textField13);
		getContentPane().add(textField14);

		textField14.setDocument(new SixDigitDocument());
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setBounds(400, 280, 200, 300);
		setVisible(true);
	}

	public static void main(String[] args) {
		new TextField_ColWidth_Document();
	}

	class SixDigitDocument extends PlainDocument {
		private static final long serialVersionUID = -952945926817174191L;

		@Override
		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException {
			char[] insertChars = str.toCharArray();
			boolean valid = true;
			boolean fit = true;
			if (insertChars.length + getLength() <= 6) {
				for (int i = 0; i < insertChars.length; i++) {
					if (!Character.isDigit(insertChars[i])) {
						valid = false;
						break;
					}
				}
			} else
				fit = false;
			if (fit && valid)
				super.insertString(offs, str, a);
			else if (!fit)
				getToolkit().beep();
		}
	}
}

